"""
APIPost JSON数据解析模块
用于解析APIPost导出的JSON文件，提取接口信息
"""

import json
from typing import Dict, List, Any, Optional


class APIPostParser:
    """APIPost JSON数据解析器"""
    
    def __init__(self, json_file_path: str):
        """
        初始化解析器
        
        Args:
            json_file_path: JSON文件路径
        """
        self.json_file_path = json_file_path
        self.data = None
        self.load_json()
    
    def load_json(self) -> None:
        """加载JSON文件"""
        try:
            with open(self.json_file_path, 'r', encoding='utf-8') as f:
                self.data = json.load(f)
        except Exception as e:
            raise Exception(f"读取JSON文件失败: {e}")
    
    def get_project_info(self) -> Dict[str, Any]:
        """获取项目基本信息"""
        return {
            'project_id': self.data.get('project_id', ''),
            'name': self.data.get('name', ''),
            'intro': self.data.get('intro', '')
        }
    
    def get_apis(self) -> List[Dict[str, Any]]:
        """获取所有API接口信息"""
        return self.data.get('apis', [])
    
    def parse_api(self, api_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        解析单个API接口数据
        
        Args:
            api_data: 单个API的数据
            
        Returns:
            解析后的API信息
        """
        # 基本信息
        basic_info = {
            'name': api_data.get('name', ''),
            'method': api_data.get('method', ''),
            'url': api_data.get('url', ''),
            'description': api_data.get('description', ''),
            'protocol': api_data.get('protocol', 'http/1.1')
        }
        
        # 请求信息
        request = api_data.get('request', {})
        request_info = {
            'headers': self._parse_parameters(request.get('header', {}).get('parameter', [])),
            'query_params': self._parse_parameters(request.get('query', {}).get('parameter', [])),
            'body': self._parse_body(request.get('body', {})),
            'auth': request.get('auth', {})
        }
        
        # 响应信息
        response = api_data.get('response', {})
        response_info = {
            'examples': self._parse_response_examples(response.get('example', []))
        }
        
        return {
            'basic_info': basic_info,
            'request_info': request_info,
            'response_info': response_info
        }
    
    def _parse_parameters(self, parameters: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """解析参数列表"""
        parsed_params = []
        for param in parameters:
            parsed_params.append({
                'key': param.get('key', ''),
                'value': param.get('value', ''),
                'description': param.get('description', ''),
                'required': param.get('not_null', 0) == 1,
                'type': param.get('field_type', 'string'),
                'enabled': param.get('is_checked', 0) == 1
            })
        return parsed_params
    
    def _parse_body(self, body_data: Dict[str, Any]) -> Dict[str, Any]:
        """解析请求体数据"""
        return {
            'mode': body_data.get('mode', ''),
            'raw': body_data.get('raw', ''),
            'parameters': self._parse_parameters(body_data.get('parameter', [])),
            'schema': body_data.get('raw_schema', {})
        }
    
    def _parse_response_examples(self, examples: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """解析响应示例"""
        parsed_examples = []
        for example in examples:
            expect = example.get('expect', {})
            parsed_examples.append({
                'name': expect.get('name', ''),
                'code': expect.get('code', '200'),
                'content_type': expect.get('content_type', 'json'),
                'raw_response': example.get('raw', ''),
                'headers': example.get('headers', []),
                'schema': expect.get('schema', {}),
                'is_default': expect.get('is_default', 0) == 1
            })
        return parsed_examples
    
    def get_all_parsed_apis(self) -> List[Dict[str, Any]]:
        """获取所有解析后的API信息"""
        apis = self.get_apis()
        parsed_apis = []
        for api in apis:
            if api.get('target_type') == 'api':  # 只处理API类型的数据
                parsed_api = self.parse_api(api)
                parsed_apis.append(parsed_api)
        return parsed_apis


if __name__ == "__main__":
    # 测试代码
    parser = APIPostParser("../input/export-demo1.json")
    project_info = parser.get_project_info()
    print("项目信息:", project_info)
    
    apis = parser.get_all_parsed_apis()
    print(f"共解析到 {len(apis)} 个接口")
    
    if apis:
        print("第一个接口信息:")
        print(apis[0])
